package com.baifc.web;

import com.baifc.datasource.SpittleRepository;
import com.baifc.entity.Spitter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;

/**
 * projectName: spring-in-action-web
 * packageName: com.baifc.web
 * Created: 2019/5/17.
 * Auther: baifc
 * Description:
 */
@Controller
@RequestMapping(value = "/spitter")
public class SpitterController {

    @Autowired
    private SpittleRepository spittleRepository;

    @RequestMapping(value = "/register", method=RequestMethod.GET)
    public String showRegistrationForm(Model model) {
        model.addAttribute("spitter", new Spitter());
        return "registerForm";
    }

    @RequestMapping(value = "/register", method=RequestMethod.POST)
    public String registrationForm(@RequestPart("profilePicture") MultipartFile profilePicture, @Valid Spitter spitter, Errors errors) {

        if (errors.hasErrors()) {
            return "registerForm";
        }

        spittleRepository.save(spitter);

        System.out.println(profilePicture.getOriginalFilename());

        try {
            profilePicture.transferTo(new File("/Users/baifc/temp2/" + profilePicture.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/spitter/register";

    }
}
